let current_package = "com.jm.video";
function bezier_curves(cp, t) {
    cx = 3.0 * (cp[1].x - cp[0].x);
    bx = 3.0 * (cp[2].x - cp[1].x) - cx;
    ax = cp[3].x - cp[0].x - cx - bx;
    cy = 3.0 * (cp[1].y - cp[0].y);
    by = 3.0 * (cp[2].y - cp[1].y) - cy;
    ay = cp[3].y - cp[0].y - cy - by;

    tSquared = t * t;
    tCubed = tSquared * t;
    result = { "x": 0, "y": 0 };
    result.x = (ax * tCubed) + (bx * tSquared) + (cx * t) + cp[0].x;
    result.y = (ay * tCubed) + (by * tSquared) + (cy * t) + cp[0].y;
    return result;
};


function sml_move(qx, qy, zx, zy, time) {
    //仿真随机带曲线滑动: qx, qy, zx, zy, time 代表起点x,起点y,终点x,终点y,过程耗时单位毫秒
    var xxy = [time];
    var point = [
        { "x": qx, "y": qy },
        { "x": random(qx - 100, qx + 100), "y": random(qy, qy + 50) },
        { "x": random(zx - 100, zx + 100), "y": random(zy, zy + 50) },
        { "x": zx, "y": zy }
    ];
    for (let i = 0; i < 1; i += 0.08) {
        xxyy = [parseInt(bezier_curves(point, i).x), parseInt(bezier_curves(point, i).y)]
        xxy.push(xxyy);
    }
    gesture.apply(null, xxy);
}
function launchAppEnhance(app_name) {
    let result;
    let thread = threads.start(function () {
        toastLog("检查是否有打开权限!");
        while (true) {
            var allow = text("允许").findOne(5000);
            if (allow) {
                sleep(1000)
                toastLog("发现允许授权!");
                allow.click();
                sleep(1000);
                thread.interrupt();
                break;
            }
        }
    });
    sleep(1000);
    if (currentPackage() != current_package) {
        result = launchApp(app_name);
        sleep(3000);
    }
    else {
        result = currentPackage();
    }
    thread.interrupt();
    return result;
}

app_func = {}
app_func.module_name = "刷宝短视频";

app_func.main = function () {
    console.log("start...");
    var open_app = launchAppEnhance(app_func.module_name);
    sleep(20 * 1000)
    if (open_app) {
        //签到任务

        for (var i = 0; i < 3; i++) {
            if (handle_sign_task() < 0) {
                continue
            }
            else {
                break
            }
        }


        //开宝箱任务
        handle_open_baoxiang_task()

        //看视频任务
        handle_watch_video_task()

    }
    else {
        toastLog("app启动失败");
    }
    console.log("end...");
}

function handle_sign_task() {
    toastLog("开始做签到任务");
    var 任务界面 = find_button_by_text("任务") || find_button_by_text("福利")
    if (任务界面) {
        click_button(任务界面.bounds())
        sleep(20000)
        // //关闭广告
        try {
            恭喜获得 = textStartsWith("恭喜获得").findOne(5000);
            if (恭喜获得) {
                恭喜获得.parent().parent().parent().child(0).click()
                toastLog("1")
            }
        } catch (e) { }
        try {
            邀请好友立得 = textStartsWith("邀请好友立得").findOne(5000);
            if (邀请好友立得) {
                let target = 邀请好友立得.parent().child(3)
                click_button(target.bounds())
                //假按钮，需要点击取消分享
                let 取消 = text("取消").findOne(5000)
                if (取消) {
                    click_button(取消.bounds())
                }
                toastLog("2")
            }
        } catch (e) { }
        close_all_ad()
        //先检查是否已经签到，立即签到控件 即使完成了也能找到
        var 已签到控件 = textStartsWith("今日已签到获得").findOne(5000)
        if (已签到控件) {
            toastLog("签到任务已完成");
        }
        else {
            var 签到按钮 = find_button_by_text("立即签到")
            if (签到按钮) {
                toastLog("开始签到");
                click_button(签到按钮.bounds())
                //看视频签到
                var 看视频签到 = find_button_by_textStartsWith("看视频签到")
                if (看视频签到) {
                    click_button(看视频签到.bounds())
                    view_ad_vedio()
                }

                //关闭邀请广告
                //关闭广告
                close_all_ad()
            }
            else {
                toastLog("签到任务失败");
                return -1
            }
        }
    }

    return 0
}

//处理倒计时广告
function close_time_adv() {
    //总时间为 广告时间X单次寻找等待时间
    let 广告时间 = 30
    for (var i = 0; i < 广告时间; i++) {
        sleep(1000)
        //每5秒检查一次关闭按钮是否出现
        if ((i + 1) % 5 == 0) {
            //寻找时间到的线索
            if (find_end_state_button() >= 0 ||
                find_X_adv_button() >= 0) {

                继续观看 = find_button_by_textStartsWith("继续观看")
                if (继续观看) {
                    click_button(继续观看.bounds())
                    continue
                }
            }
            if (is_mainAct()) { //任务act 也应该视为广告已不存在
                return 0
            }
        }
    }
    return -1;
}

function is_mainAct() {
    sleep(1000)
    var curact = currentActivity();
    if (curact != "com.jm.video.ui.main.MainActivity" && curact != "com.jm.video.ui.web.WebViewActivity") {
        toastLog("不在主界面")
        return false
    }
    else {
        toastLog("当前是主界面")
        return true
    }
}

//寻找 没有倒计时存在后  back
function find_end_state_button() {
    var back_button = text("点击重播").findOne(1000)
    var cli_button = null
    if (back_button) {
        toastLog("发现关闭时机");
        back()
        return 0
    }//出现刚开始是关闭广告过两秒才开始倒计时的情况
    else if (cli_button = text("关闭广告").findOne(1000)) {
        sleep(3000)
        cli_button = text("关闭广告").findOne(1000)
        if (cli_button) {
            toastLog("关闭广告");
            click_button(cli_button.bounds())
            return 0
        }
    }
    else {
        //寻找关闭按钮
        关闭 = text("关闭").findOne(1000)
        if (关闭) { //有假关闭按钮统一back
            back()
            return 0
        }
    }
    return -1
}

//寻找img类型关闭按钮
function find_X_adv_button() {
    //点击下载出现的时候   倒计时控件不存在的时候
    var close =
        id("tt_video_ad_close").findOne(1000) ||
        id("tt_video_ad_close_layout").findOne(1000)
    if (close) {
        toastLog("发现关闭按钮");
        click_button(close.bounds());
        return 0
    }
    else {
        //支付宝三连
        //弹支付宝   取消安装   关闭按钮
        try {
            取消 = text("取消").findOne(500)
            if (取消) {
                click_button(取消.bounds())
                toastLog("11")
            }
        } catch (error) {
        }
        try {
            关闭 = text("关闭").findOne(500)
            if (关闭) {
                click_button(关闭.bounds())
                toastLog("22")
            }
        } catch (error) {
        }
        try {//支付宝
            if (currentPackage() != 'com.jm.video') {
                sleep(2000)
                back()
                sleep(2000)
                继续 = textStartsWith("继续").findOne(1000)
                toastLog("33")
                if (继续) {
                    click_button(继续.bounds())
                    toastLog("44")
                }
            }
        } catch (error) {
        }
    }
    return -1
}

function view_ad_vedio() {
    sleep(3000);
    //获取视频秒数
    var count_item = id("tt_top_countdown").findOne(8000);
    var count_item2 = id("tt_top_skip").findOne(1000);
    var count_item3 = id("tt_reward_ad_countdown").findOne(1000);
    var count = 60;
    if (count_item) {
        sleep(1000);
        count = count_item.text().replace("秒", "");
    }
    else if (count_item2) {
        sleep(1000);
        count = count_item2.text().replace(" | 跳过", "");
    }
    else if (count_item3) {
        sleep(1000);
        count = count_item3.text();
    }
    toastLog("等待广告播放结束，还剩" + count + "秒");
    sleep((parseInt(count) + 5) * 1000);
    var close = id("reward_ad_close").findOne(5000) || id("tt_video_ad_close_layout").findOne(1000) || id("tt_video_ad_close").findOne(1000);
    if (close) {
        toastLog("发现关闭按钮");
        sleep(1000);
        close.click();
    }
}

function handle_open_baoxiang_task() {
    toastLog("开始做开宝箱任务");
    var 任务界面 = find_button_by_text("任务") || find_button_by_text("福利")
    if (任务界面) {
        click_button(任务界面.bounds())
        //关闭广告
        close_all_ad()
        var 宝箱控件 = find_button_by_text("开箱领元宝")
        if (宝箱控件) {
            toastLog("开始领宝箱");
            click_button(宝箱控件.bounds())
            //关闭广告
            var 邀请广告 = find_button_by_textStartsWith("邀请好友")
            var 关闭控件 = 邀请广告.parent().child(0)
            关闭控件.click()
            toastLog("宝箱任务完成");
        }
        else {
            toastLog("宝箱还不能领");
        }

        //看视频赚元宝
        去观看 = text("去观看").findOne(2000)
        if (去观看) {
            try {
                去观看.click()
                close_time_adv()
            } catch (error) { }
        }

        待领取 = text("待领取").findOne(2000)
        if (待领取) {
            try {
                待领取.click()
                close_time_adv()
            } catch (error) { }
        }

        // handle_withdraw()
    }

    return 0
}

function handle_withdraw() {
    toastLog("开始提现任务")
    提现 = text("提现").findOne(2000)
    if (提现) {
        提现.click()
        sleep(5000)
        for (var i = 0; i < 2; i++) {
            立即观看 = text("立即观看").findOne(2000)
            if (立即观看) {
                立即观看.click()
                close_time_adv()
                close_all_ad()
            }
            else {
                break
            }
        }
    }

    back()

    return 0
}

function handle_watch_video_task() {
    toastLog("开始做看视频任务");
    var 首页 = find_button_by_text("首页")
    if (首页) {
        click_button(首页.bounds())
        close_all_ad()
        var count = 600
        var index = 0;
        var random_min = 1000
        var random_max = 6000
        var w = device.width
        var h = device.height

        if (count == 0) { return }
        toastLog("即将滑动" + count + "次！");
        while (index <= count) {
            sml_move(w / 2, h * 0.8 + h * random() * 0.1, w / 2, h * 0.15, 200 + 600 * random());
            var 头像 = id('iv_author_avatar').findOne(2000)
            if (头像) {
                back()
            }
            var random_time = random(random_min, random_max);
            toastLog("观看" + app_func.module_name + "第" + index + "/" + count + "个视频中...");
            toastLog("预计时长" + (random_time / 1000) + "秒~");
            sleep(random_time);
            index++;
        }
    }
    else {
        toastLog("没找到首页任务失败");
        return -1
    }
    toastLog("视频任务完成");
    return 0
}

function find_button_by_text(textstr) {
    toastLog("寻找按钮:" + textstr);
    var task_button = null
    for (var i = 0; i < 2; i++) {
        task_button = text(textstr).findOne(3000);
        if (task_button) {
            console.log("找到控件text:", task_button.text());
            break;
        }
        else {
            console.log("第" + (i + 1) + "次未找到");
            sleep(1000)
            continue;
        }
    }

    return task_button
}

function find_button_by_textStartsWith(textstr) {
    toastLog("寻找按钮:" + textstr);
    var task_button = null
    for (var i = 0; i < 2; i++) {
        task_button = textStartsWith(textstr).findOne(3000);
        if (task_button) {
            console.log("找到控件text:", task_button.text());
            break;
        }
        else {
            console.log("第" + (i + 1) + "次未找到");
            sleep(1000)
            continue;
        }
    }
    sleep(1000)
    return task_button
}

function click_button(bounds) {
    toastLog("点击按钮:" + bounds.centerX() + bounds.centerY());
    sleep(1000);
    click(bounds.centerX(), bounds.centerY());
    sleep(2000)
}

//关闭各种弹窗广告
function close_all_ad() {
    //邀请任务弹窗
    toastLog("尝试关闭广告..")
    try { id("imgClose").findOne(2000).click(); } catch (e) { }
    try { textStartsWith('今日任务完成了').findOne(500).click(); } catch (e) { }
    try { text('我知道了').findOne(500).click(); } catch (e) { }
    try { text('点击刷新').findOne(500).click(); } catch (e) { }
    try { text('跳过').findOne(500).click(); } catch (e) { }
    try { text('禁止').findOne(500).click(); } catch (e) { }
    try {
        邀请好友最高 = textStartsWith("邀请好友最高").findOne(500)
        if (邀请好友最高) {
            邀请好友最高.parent().child(0).click()
            toastLog("找到控件")
            toastLog("4")
        }
        else {
            toastLog("没找到")
        }

    } catch (e) { }
    try {
        恭喜获得 = textStartsWith("恭喜获得").findOne(500);
        if (恭喜获得) {
            恭喜获得.parent().parent().parent().child(0).click()
            toastLog("1")
        }
    } catch (e) { }
    try {
        恭喜您获得 = textStartsWith("恭喜您获得").findOne(500);
        if (恭喜您获得) {
            恭喜您获得.parent().child(0).click()
            toastLog("3")
        }
    } catch (e) { }
    try {
        邀请好友立得 = textStartsWith("邀请好友立得").findOne(500);
        if (邀请好友立得) {
            //    邀请好友.parent().parent().parent().child(0).click()
            let target = 邀请好友立得.parent().child(3)
            click_button(target.bounds())
            let 取消 = text("取消").findOne(5000)
            if (取消) {
                click_button(取消.bounds())
            }
            toastLog("2")
        }
    } catch (e) { }

    try {
        击败了全国 = textContains("击败了全国").findOne(500);
        if (击败了全国) {
            击败了全国.parent().child(5).click()
            toastLog("5")
        }
    } catch (e) { }

}

try {
    app_func.main();
} catch (error) {
    toastLog(error);
}

var storage = storages.create("xiangxiangyuedu");
storage.put("script_running_status", "end");